package com.freak.httpmanager.log;


import com.freak.httpmanager.HttpMethods;

import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Http网络请求日志格式
 *
 * @author freak
 * @date 2022/09/12
 */
public class HttpLogger implements HttpLoggingInterceptor.Logger {
    // 使用StringBuffer保证线程安全
    private static final StringBuffer STRING_BUFFER = new StringBuffer();

    @Override
    public void log(String message) {
        // 请求或者响应开始
        if (message.startsWith("--> POST")) {
            STRING_BUFFER.setLength(0);
            if (message.endsWith("http/1.1")) {
                String url = message.substring(message.indexOf("http"), message.lastIndexOf("http/1.1"));
                STRING_BUFFER.append("请求地址--> " + UrlUtil.getURLDecoderString(url).concat("\n"));
            }
        }
        // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
        if ((message.startsWith("{") && message.endsWith("}"))
                || (message.startsWith("[") && message.endsWith("]"))) {
            message = JsonUtil.formatJson(message);
        }
        STRING_BUFFER.append(message.concat("\n"));
        // 请求或者响应结束，打印整条日志
        if (message.startsWith("<-- END HTTP")) {
            switch (HttpMethods.getInstanceBuilder().getLogLevel()) {
                case LogLevel.ERROR:
                    LogUtil.e(STRING_BUFFER.toString());
                    break;
                case LogLevel.DEBUG:
                    LogUtil.d(STRING_BUFFER.toString());
                    break;
                case LogLevel.WARM:
                    LogUtil.w(STRING_BUFFER.toString(), null);
                    break;
                case LogLevel.INFO:
                    LogUtil.i(STRING_BUFFER.toString());
                    break;
                default:
                    break;
            }
        }
    }
}
